<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数独游戏 2.0</title>
    <style>
        /* 关卡选择样式 */
        .levels-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 20px;
            max-width: 1200px;
            width: 100%;
            padding: 20px;
        }

        .level-card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

        .level-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.2);
        }

        .level-card.locked {
            opacity: 0.7;
            cursor: not-allowed;
        }

        .level-card.locked::before {
            content: '🔒';
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 2em;
            color: #2c3e50;
        }

        .level-number {
            font-size: 1.5em;
            font-weight: bold;
            color: #2c3e50;
            margin-bottom: 10px;
        }

        .difficulty {
            font-size: 0.9em;
            color: #666;
            margin-bottom: 15px;
        }

        .stars {
            color: #ffd700;
            font-size: 1.2em;
            margin-bottom: 10px;
        }

        .completion {
            font-size: 0.8em;
            color: #4a90e2;
        }

        .completed {
            position: absolute;
            top: 10px;
            right: 10px;
            background: #4CAF50;
            color: white;
            padding: 5px 10px;
            border-radius: 10px;
            font-size: 0.8em;
        }

        .completion-time {
            color: #2980b9;
            margin-top: 5px;
            font-size: 0.9em;
        }

        .victory-animation {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            color: white;
            z-index: 1000;
            animation: fadeIn 0.5s ease-in;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .victory-text {
            font-size: 2em;
            margin-bottom: 20px;
            animation: scaleUp 0.5s ease-out;
        }

        @keyframes scaleUp {
            from { transform: scale(0); }
            to { transform: scale(1); }
        }

        @media (max-width: 600px) {
            .levels-container {
                grid-template-columns: repeat(2, 1fr);
                padding: 10px;
            }
        }

        body {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            margin: 0;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            font-family: 'Microsoft YaHei', Arial, sans-serif;
        }

        .game-container {
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            transition: transform 0.3s ease;
        }

        .game-container:hover {
            transform: translateY(-5px);
        }

        .controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 10px;
        }

        .lives {
            display: flex;
            gap: 5px;
            margin-right: 10px;
        }

        .heart {
            color: #ff4d4d;
            font-size: 1.5em;
        }

        .heart.empty {
            color: #ccc;
        }

        .custom-alert {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(255, 255, 255, 0.95);
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 5px 25px rgba(0, 0, 0, 0.2);
            text-align: center;
            z-index: 1001;
        }

        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
        }

        .custom-alert h2 {
            color: #2c3e50;
            margin-bottom: 20px;
            font-size: 24px;
        }

        .custom-alert p {
            color: #34495e;
            margin-bottom: 25px;
            font-size: 18px;
        }

        .custom-alert .buttons {
            display: flex;
            justify-content: center;
            gap: 15px;
        }

        .custom-alert button {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s ease;
        }

        .custom-alert .next-level {
            background: #2ecc71;
            color: white;
        }

        .custom-alert .back-to-levels {
            background: #3498db;
            color: white;
        }

        .custom-alert button:hover {
            transform: translateY(-2px);
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2);
        }

        .custom-alert h2 {
            color: #2c3e50;
            margin-bottom: 15px;
        }

        .custom-alert p {
            color: #666;
            margin-bottom: 20px;
        }

        .custom-alert button {
            background: #4CAF50;
            color: white;
            border: none;
            padding: 10px 20px;
            margin: 0 10px;
            border-radius: 5px;
            cursor: pointer;
            transition: background 0.3s ease;
        }

        .custom-alert button:hover {
            background: #45a049;
        }

        .overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 999;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .custom-alert {
            transform: translate(-50%, -50%);
            background: rgba(255, 255, 255, 0.95);
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 5px 25px rgba(0, 0, 0, 0.2);
            text-align: center;
            z-index: 1000;
            animation: fadeIn 0.3s ease;
        }

        .custom-alert h2 {
            color: #2c3e50;
            margin-bottom: 15px;
        }

        .custom-alert .buttons {
            display: flex;
            gap: 15px;
            justify-content: center;
            margin-top: 20px;
        }

        .custom-alert button {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            background: #4a90e2;
            color: white;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .custom-alert button:hover {
            background: #357abd;
            transform: translateY(-2px);
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translate(-50%, -60%); }
            to { opacity: 1; transform: translate(-50%, -50%); }
        }

        /* 添加遮罩层样式 */
        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 999;
            animation: fadeIn 0.3s ease;
        }

        .custom-alert .next-level {
            background: #4CAF50;
            color: white;
        }

        .custom-alert .back-to-levels {
            background: #2196F3;
            color: white;
        }

        .custom-alert button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 999;
        }

        @media (max-width: 600px) {
            .custom-alert {
                min-width: 250px;
                padding: 15px;
            }
            .custom-alert button {
                padding: 8px 16px;
                font-size: 14px;
            }
        }

        .completion-time {
            color: #2980b9;
            margin-top: 5px;
            font-size: 0.9em;
        }

        .timer {
            font-size: 1.3em;
            color: #2c3e50;
            font-weight: bold;
            padding: 8px 15px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .difficulty-select {
            padding: 8px 15px;
            border-radius: 8px;
            border: 2px solid #e9ecef;
            background: #fff;
            color: #2c3e50;
            font-size: 1em;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .difficulty-select:hover {
            border-color: #4a90e2;
        }

        .grid {
            display: grid;
            grid-template-columns: repeat(9, 1fr);
            gap: 0;
            background-color: #e0e0e0;
            border: 1px solid #2c3e50;
            margin-bottom: 20px;
            padding: 1px;
            border-radius: 5px;
            position: relative;
        }

        .cell {
            width: 45px;
            height: 45px;
            background: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2em;
            font-weight: 500;
            color: #2c3e50;
            cursor: pointer;
            transition: all 0.2s ease;
            border: 1px solid #e0e0e0;
        }

        .cell:nth-child(3n) {
            border-right: 1px solid #a0a0a0;
        }

        .cell:nth-child(n+19):nth-child(-n+27),
        .cell:nth-child(n+46):nth-child(-n+54) {
            border-bottom: 1px solid #a0a0a0;
        }

        .cell:hover:not(.fixed) {
            background: #f0f4f8;
        }

        .cell.selected {
            background: #e3f2fd;
            color: #1976D2;
        }

        .cell.fixed {
            color: #34495e;
            font-weight: bold;
            background: #f8f9fa;
        }

        .cell.error {
            background: #ffebee;
            color: #d32f2f;
        }

        .cell.same-number {
            background: #ffd8b5;
            transition: background-color 0.3s ease;
        }

        .number-pad {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
            margin-bottom: 20px;
        }

        .number-btn {
            padding: 15px 25px;
            font-size: 1.2em;
            border: none;
            background: #f8f9fa;
            color: #2c3e50;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .number-btn:hover {
            background: #e9ecef;
            transform: translateY(-2px);
        }

        .action-buttons {
            display: flex;
            gap: 15px;
            justify-content: center;
        }

        .action-btn {
            padding: 12px 25px;
            font-size: 1em;
            border: none;
            background: #4a90e2;
            color: white;
            cursor: pointer;
            border-radius: 8px;
            transition: all 0.3s ease;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .action-btn:hover {
            background: #357abd;
            transform: translateY(-2px);
        }

        .hint-btn {
            background: #ffd43b;
        }

        .hint-btn:hover {
            background: #fcc419;
        }

        @media (max-width: 600px) {
            .levels-container {
                grid-template-columns: repeat(2, 1fr);
                padding: 10px;
                gap: 10px;
            }

            .level-card {
                padding: 15px;
            }

            .level-number {
                font-size: 1.2em;
            }

            .stars {
                font-size: 1em;
            }

            .game-container {
                padding: 15px;
                width: 95%;
                max-width: 400px;
                margin: 0 auto;
            }

            .grid {
                gap: 1px;
                padding: 2px;
                @media (max-width: 600px) {
                    .grid {
                        gap: 1px;
                        background-color: #2c3e50;
                        border: 1px solid #2c3e50;
                        padding: 1px;
                    }

                    .cell {
                        width: 35px;
                        height: 35px;
                        font-size: 1.1em;
                        border-right: 1px solid #e0e0e0;
                        border-bottom: 1px solid #e0e0e0;
                    }

                    .cell:nth-child(3n) {
                        border-right: 1px solid #2c3e50;
                    }

                    .cell:nth-child(n+19):nth-child(-n+27),
                    .cell:nth-child(n+46):nth-child(-n+54) {
                        border-bottom: 1px solid #2c3e50;
                    }

                    .number-pad {
                        gap: 8px;
                        margin: 10px 0;
                    }

                    .number-btn {
                        padding: 10px;
                        font-size: 1.1em;
                    }
                }
            }

            .cell {
                width: 32px;
                height: 32px;
                font-size: 0.9em;
            }

            .number-pad {
                gap: 5px;
                margin: 15px 0;
            }

            .number-btn {
                padding: 8px 12px;
                font-size: 1em;
            }

            .action-buttons {
                gap: 10px;
            }

            .action-btn {
                padding: 8px 15px;
                font-size: 0.9em;
            }

            .timer {
                font-size: 1em;
            }
        }

        @media (max-width: 350px) {
            .cell {
                width: 28px;
                height: 28px;
                font-size: 0.8em;
            }

            .number-btn {
                padding: 6px 10px;
                font-size: 0.9em;
            }
        }
    </style>
</head>
<body>
    <div class="levels-container" id="levelsContainer" style="display: none;"></div>
    <div class="game-container" style="display: none;">
        <div id="customAlert" class="custom-alert" style="display: none;">
            <h2>恭喜完成！</h2>
            <p id="completionTime"></p>
            <div class="buttons">
                
                <button class="back-to-levels" onclick="backToLevels()">选择关卡</button>
            </div>
        </div>
        <div id="overlay" class="overlay" style="display: none;"></div>
        <div class="controls">
            <div class="lives">
                <span class="heart">❤️</span>
                <span class="heart">❤️</span>
                <span class="heart">❤️</span>
            </div>
            <div class="timer">时间: 00:00</div>
            <div class="current-level">当前关卡: 1</div>
        </div>
        <div class="grid" id="sudokuGrid"></div>
        <div class="number-pad">
            <button class="number-btn" onclick="setNumber(1)">1</button>
            <button class="number-btn" onclick="setNumber(2)">2</button>
            <button class="number-btn" onclick="setNumber(3)">3</button>
            <button class="number-btn" onclick="setNumber(4)">4</button>
            <button class="number-btn" onclick="setNumber(5)">5</button>
            <button class="number-btn" onclick="setNumber(6)">6</button>
            <button class="number-btn" onclick="setNumber(7)">7</button>
            <button class="number-btn" onclick="setNumber(8)">8</button>
            <button class="number-btn" onclick="setNumber(9)">9</button>
        </div>
        <div class="action-buttons">
            <button class="action-btn" onclick="backToLevels()">返回关卡</button>
            
        </div>
    </div>

    <script>
        // 游戏状态变量
        let selectedCell = null;
        let timer = null;
        let seconds = 0;
        let board = [];
        let solution = [];
        let mistakes = 0;
        const maxMistakes = 3;

        // 初始化数字按钮
        function initializeNumberButtons() {
            const numberPad = document.createElement('div');
            numberPad.className = 'number-pad';
            
            for (let i = 1; i <= 9; i++) {
                const button = document.createElement('button');
                button.className = 'number-btn';
                button.textContent = i;
                button.onclick = () => handleNumberClick(i);
                numberPad.appendChild(button);
            }

            document.querySelector('.game-container').appendChild(numberPad);
        }

        function backToLevels(){
            // 停止计时器
            stopTimer();
            // 弹出层消失 关卡列表页面出现
            document.getElementById('levelsContainer').style.display = 'grid';
            // 游戏页面消失
            document.querySelector('.game-container').style.display = 'none';
            // 隐藏弹窗和遮罩
            document.getElementById('overlay').style.display = 'none';
            document.getElementById('customAlert').style.display = 'none';
            // 重新渲染关卡
            renderLevels();
        }
        // 处理数字按钮点击
        function handleNumberClick(number) {
            if (selectedCell && !selectedCell.classList.contains('fixed')) {
                onNumberInput(selectedCell, number);
                highlightSameNumbers(number);
            }
        }

        // 处理单元格点击
        function handleCellClick(cell) {
            // 移除所有单元格的选中状态
            const cells = document.getElementsByClassName('cell');
            Array.from(cells).forEach(c => c.classList.remove('selected'));
            
            // 设置新的选中单元格
            selectedCell = cell;
            cell.classList.add('selected');

            // 高亮相同数字
            if (cell.textContent) {
                highlightSameNumbers(cell.textContent);
            } else {
                clearSameNumberHighlight();
            }
        }

        
        // 移除相同数字高亮
        function removeSameNumberHighlight() {
            const cells = document.querySelectorAll('.cell');
            cells.forEach(cell => {
                cell.classList.remove('same-number');
            });
        }

        // 初始化游戏网格
        function initializeGrid() {
            const grid = document.createElement('div');
            grid.className = 'grid';

            for (let i = 0; i < 81; i++) {
                const cell = document.createElement('div');
                cell.className = 'cell';
                cell.onclick = () => handleCellClick(cell);
                grid.appendChild(cell);
            }

            document.querySelector('.game-container').appendChild(grid);
        }

        // 检查数独是否完成
        function checkSudokuCompletion() {
            // 检查每个单元格是否都已填写
            for (let i = 0; i < 81; i++) {
                const cell = document.querySelectorAll('.cell')[i];
                if (!cell.textContent || cell.classList.contains('error')) {
                    return false;
                }
            }

            // 检查行、列和九宫格是否符合规则
            for (let i = 0; i < 9; i++) {
                if (!checkRow(i) || !checkColumn(i) || !checkBox(i)) {
                    return false;
                }
            }

            return true;
        }

        // 在填入数字后检查游戏状态
        function onNumberInput(cell, number) {
            cell.textContent = number;
            validateCell(cell);

            // 检查游戏是否完成
            if (checkSudokuCompletion()) {
                onGameComplete();
            }
        }

        // 验证单元格
        function validateCell(cell) {
            const row = Math.floor(Array.from(cell.parentNode.children).indexOf(cell) / 9);
            const col = Array.from(cell.parentNode.children).indexOf(cell) % 9;
            const num = cell.textContent;

            // 移除之前的错误标记
            cell.classList.remove('error');

            // 检查行
            if (!isValidInRow(row, col, num)) {
                cell.classList.add('error');
                return false;
            }

            // 检查列
            if (!isValidInColumn(row, col, num)) {
                cell.classList.add('error');
                return false;
            }

            // 检查九宫格
            if (!isValidInBox(row, col, num)) {
                cell.classList.add('error');
                return false;
            }

            return true;
        }

        // 检查行是否有效
        function isValidInRow(row, col, num) {
            const cells = document.querySelectorAll('.cell');
            for (let i = 0; i < 9; i++) {
                if (i !== col && cells[row * 9 + i].textContent === num) {
                    return false;
                }
            }
            return true;
        }

        // 检查列是否有效
        function isValidInColumn(row, col, num) {
            const cells = document.querySelectorAll('.cell');
            for (let i = 0; i < 9; i++) {
                if (i !== row && cells[i * 9 + col].textContent === num) {
                    return false;
                }
            }
            return true;
        }

        // 检查九宫格是否有效
        function isValidInBox(row, col, num) {
            const boxRow = Math.floor(row / 3) * 3;
            const boxCol = Math.floor(col / 3) * 3;
            const cells = document.querySelectorAll('.cell');

            for (let i = 0; i < 3; i++) {
                for (let j = 0; j < 3; j++) {
                    const currentRow = boxRow + i;
                    const currentCol = boxCol + j;
                    if (currentRow !== row || currentCol !== col) {
                        if (cells[currentRow * 9 + currentCol].textContent === num) {
                            return false;
                        }
                    }
                }
            }
            return true;
        }

        // 更新生命值显示
        function updateLives() {
            const hearts = document.querySelectorAll('.heart');
            const remainingLives = maxMistakes - mistakes;
            hearts.forEach((heart, index) => {
                heart.textContent = index < remainingLives ? '❤️' : '🤍';
            });
        }

        // 清除所有相同数字的高亮
        function clearSameNumberHighlight() {
            const cells = document.querySelectorAll('.cell');
            cells.forEach(cell => cell.classList.remove('same-number'));
        }

        // 高亮显示相同数字
        function highlightSameNumbers(number) {
            clearSameNumberHighlight();
            if (!number) return;
            
            const cells = document.querySelectorAll('.cell');
            cells.forEach(cell => {
                if (cell.textContent === number.toString()) {
                    cell.classList.add('same-number');
                }
            });
        }

        // 设置数字
        function setNumber(num) {
            if (!selectedCell || selectedCell.classList.contains('fixed')) return;
            
            const index = Array.from(selectedCell.parentNode.children).indexOf(selectedCell);
            const row = Math.floor(index / 9);
            const col = index % 9;
            
            // 高亮显示相同数字
            highlightSameNumbers(num);
            
            if (solution[row][col] === num) {
                selectedCell.textContent = num;
                board[row][col] = num;
                selectedCell.classList.remove('error');
                
                if (isBoardFull() && isSolutionCorrect()) {
                    stopTimer();
                    const currentLevel = getCurrentLevel();
                    const timeTaken = seconds;
                    const minutes = Math.floor(timeTaken / 60);
                    const remainingSeconds = timeTaken % 60;
                    const timeString = `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
                    
                    document.getElementById('overlay').style.display = 'block';
                    document.getElementById('customAlert').style.display = 'block';
                    document.getElementById('completionTime').textContent = `完成用时: ${timeString}`;
                    
                    // 保存完成时间
                    const levelData = JSON.parse(localStorage.getItem('sudokuLevels') || '{}');
                    if (!levelData[currentLevel] || timeTaken < levelData[currentLevel].time) {
                        levelData[currentLevel] = {
                            completed: true,
                            time: timeTaken
                        };
                        localStorage.setItem('sudokuLevels', JSON.stringify(levelData));
                    }
                    
                    stopTimer();
                    saveProgress();
                }
            } else {
                mistakes++;
                selectedCell.classList.add('error');
                updateLives();
                if (mistakes >= maxMistakes) {
                    setTimeout(() => {
                        alert('游戏结束！你已用完所有生命值。');
                        newGame();
                    }, 100);
                }
            }
        }

        // 关卡数据
        const levels = Array.from({length: 30}, (_, i) => ({
            id: i + 1,
            difficulty: calculateDifficulty(i + 1),
            stars: calculateStars(i + 1),
            completed: false,
            locked: i > 0 // 第一关解锁，其他关卡锁定
        }));

        // 计算难度
        function calculateDifficulty(level) {
            if (level <= 5) return '简单';
            if (level <= 12) return '中等';
            if (level <= 20) return '困难';
            return '专家';
        }

        // 计算星级
        function calculateStars(level) {
            return Math.min(Math.ceil(level / 6), 5);
        }

        // 渲染关卡
        function renderLevels() {
            const container = document.getElementById('levelsContainer');
            container.innerHTML = '';
            const completionTimes = JSON.parse(localStorage.getItem('sudokuCompletionTimes') || '{}');

            levels.forEach(level => {
                const card = document.createElement('div');
                card.className = `level-card ${level.locked ? 'locked' : ''}`;
                
                if (!level.locked) {
                    card.addEventListener('click', () => startLevel(level.id));
                }

                const completionTime = completionTimes[level.id];
                const timeDisplay = completionTime ? `<div class="completion-time">完成用时: ${Math.floor(completionTime / 60)}:${(completionTime % 60).toString().padStart(2, '0')}</div>` : '';

                card.innerHTML = `
                    <div class="level-number">关卡 ${level.id}</div>
                    <div class="difficulty">${level.difficulty}</div>
                    ${level.completed ? '<div class="completed">已完成</div>' + timeDisplay : ''}
                `;

                container.appendChild(card);
            });
        }

        // 开始关卡
        function startLevel(levelId) {
            // 保存当前关卡ID到本地存储
            localStorage.setItem('currentLevel', levelId);
            // 切换界面显示
            document.getElementById('levelsContainer').style.display = 'none';
            document.querySelector('.game-container').style.display = 'block';
            document.querySelector('.current-level').textContent = `当前关卡: ${levelId}`;
            
            // 确保网格已创建
            const grid = document.getElementById('sudokuGrid');
            grid.innerHTML = '';
            for (let i = 0; i < 81; i++) {
                const cell = document.createElement('div');
                cell.className = 'cell';
                grid.appendChild(cell);
            }
            
            newGame();
        }



        // 从本地存储加载进度
        function loadProgress() {
            const savedProgress = localStorage.getItem('sudokuProgress');
            if (savedProgress) {
                const progress = JSON.parse(savedProgress);
                progress.forEach(levelId => {
                    const level = levels[levelId - 1];
                    if (level) {
                        level.completed = true;
                        // 解锁下一关
                        if (levels[levelId]) {
                            levels[levelId].locked = false;
                        }
                    }
                });
            }
        }

        // 初始化页面
        window.onload = function() {
            loadProgress();
            renderLevels();
            document.getElementById('levelsContainer').style.display = 'grid';
        };

        // 获取当前关卡信息
        function getCurrentLevel() {
            const levelId = localStorage.getItem('currentLevel') || 1;
            return parseInt(levelId);
        }

        // 根据关卡返回难度
        function getDifficultyByLevel(level) {
            if (level <= 5) return 'easy';
            if (level <= 12) return 'medium';
            if (level <= 20) return 'hard';
            return 'expert';
        }

        // 根据难度返回要移除的单元格数量
        function getDifficultyRemoval() {
            const currentLevel = getCurrentLevel();
            const difficulty = getDifficultyByLevel(currentLevel);
            const difficulties = {
                'easy': 30,
                'medium': 40,
                'hard': 50,
                'expert': 60
            };
            return difficulties[difficulty];
        }

        // 保存游戏进度
        function saveProgress() {
            const currentLevel = getCurrentLevel();
            const savedProgress = localStorage.getItem('sudokuProgress') || '[]';
            const progress = new Set(JSON.parse(savedProgress));
            progress.add(currentLevel);
            localStorage.setItem('sudokuProgress', JSON.stringify([...progress]));

            // 保存完成时间
            const completionTimes = JSON.parse(localStorage.getItem('sudokuCompletionTimes') || '{}');
            completionTimes[currentLevel] = seconds;
            localStorage.setItem('sudokuCompletionTimes', JSON.stringify(completionTimes));

            // 更新当前关卡状态
            const level = levels[currentLevel - 1];
            if (level) {
                level.completed = true;
                // 解锁下一关
                if (levels[currentLevel]) {
                    levels[currentLevel].locked = false;
                }
            }
        }
             
        

        // 初始化游戏
        function initGame() {
            board = generateSudoku();
            solution = JSON.parse(JSON.stringify(board));
            const cells = document.getElementsByClassName('cell');
            const cellsToRemove = getDifficultyRemoval();
            
            // 随机移除单元格
            const positions = shuffle(Array.from({length: 81}, (_, i) => i));
            for (let i = 0; i < cellsToRemove; i++) {
                const pos = positions[i];
                const row = Math.floor(pos / 9);
                const col = pos % 9;
                board[row][col] = 0;
            }
            
            // 更新界面
            for (let i = 0; i < 9; i++) {
                for (let j = 0; j < 9; j++) {
                    const cell = cells[i * 9 + j];
                    cell.textContent = board[i][j] || '';
                    cell.className = 'cell' + (board[i][j] ? ' fixed' : '');
                    cell.onclick = () => selectCell(cell);
                }
            }
            
            seconds = 0;
            document.querySelector('.timer').textContent = '时间: 00:00';
        }

        // 生成数独
        function generateSudoku() {
            const grid = Array(9).fill().map(() => Array(9).fill(0));
            fillGrid(grid);
            return grid;
        }

        // 填充数独网格
        function fillGrid(grid) {
            for (let i = 0; i < 9; i++) {
                for (let j = 0; j < 9; j++) {
                    if (grid[i][j] === 0) {
                        const nums = shuffle([1,2,3,4,5,6,7,8,9]);
                        for (let num of nums) {
                            if (isValid(grid, i, j, num)) {
                                grid[i][j] = num;
                                if (fillGrid(grid)) return true;
                                grid[i][j] = 0;
                            }
                        }
                        return false;
                    }
                }
            }
            return true;
        }

        // 检查数字是否有效
        function isValid(grid, row, col, num) {
            // 检查行
            for (let x = 0; x < 9; x++) {
                if (grid[row][x] === num) return false;
            }
            
            // 检查列
            for (let x = 0; x < 9; x++) {
                if (grid[x][col] === num) return false;
            }
            
            // 检查3x3方格
            const startRow = Math.floor(row / 3) * 3;
            const startCol = Math.floor(col / 3) * 3;
            for (let i = 0; i < 3; i++) {
                for (let j = 0; j < 3; j++) {
                    if (grid[i + startRow][j + startCol] === num) return false;
                }
            }
            
            return true;
        }

       

        // 打乱数组
        function shuffle(array) {
            for (let i = array.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [array[i], array[j]] = [array[j], array[i]];
            }
            return array;
        }

        // 启动计时器
        function startTimer() {
            if (timer) {
                clearInterval(timer);
            }
            timer = setInterval(() => {
                seconds++;
                const minutes = Math.floor(seconds / 60);
                const remainingSeconds = seconds % 60;
                document.querySelector('.timer').textContent = 
                    `时间: ${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
            }, 1000);
        }

        // 停止计时器
        function stopTimer() {
            if (timer) {
                clearInterval(timer);
                timer = null;
            }
        }

        // 一键填满所有单元格
        function fillAllCells() {
            const cells = document.getElementsByClassName('cell');
            for (let i = 0; i < 9; i++) {
                for (let j = 0; j < 9; j++) {
                    const cell = cells[i * 9 + j];
                    if (!cell.classList.contains('fixed')) {
                        cell.textContent = solution[i][j];
                        board[i][j] = solution[i][j];
                        cell.classList.remove('error');
                    }
                }
            }
        }

        // 开始新游戏
        function newGame() {
            mistakes = 0;
            updateLives();
            initGame();
            startTimer();
        }

        // 初始化游戏
        function initGame() {
            board = generateSudoku();
            solution = JSON.parse(JSON.stringify(board));
            const cells = document.getElementsByClassName('cell');
            const cellsToRemove = getDifficultyRemoval();
            
            // 随机移除单元格
            const positions = shuffle(Array.from({length: 81}, (_, i) => i));
            for (let i = 0; i < cellsToRemove; i++) {
                const pos = positions[i];
                const row = Math.floor(pos / 9);
                const col = pos % 9;
                board[row][col] = 0;
            }
            
            // 更新界面
            for (let i = 0; i < 9; i++) {
                for (let j = 0; j < 9; j++) {
                    const cell = cells[i * 9 + j];
                    cell.textContent = board[i][j] || '';
                    cell.className = 'cell' + (board[i][j] ? ' fixed' : '');
                    cell.onclick = () => selectCell(cell);
                }
            }
            
            seconds = 0;
            document.querySelector('.timer').textContent = '时间: 00:00';
        }

        // 生成数独
        function generateSudoku() {
            const grid = Array(9).fill().map(() => Array(9).fill(0));
            fillGrid(grid);
            return grid;
        }

        // 填充数独网格
        function fillGrid(grid) {
            for (let i = 0; i < 9; i++) {
                for (let j = 0; j < 9; j++) {
                    if (grid[i][j] === 0) {
                        const nums = shuffle([1,2,3,4,5,6,7,8,9]);
                        for (let num of nums) {
                            if (isValid(grid, i, j, num)) {
                                grid[i][j] = num;
                                if (fillGrid(grid)) return true;
                                grid[i][j] = 0;
                            }
                        }
                        return false;
                    }
                }
            }
            return true;
        }

        // 检查数字是否有效
        function isValid(grid, row, col, num) {
            // 检查行
            for (let x = 0; x < 9; x++) {
                if (grid[row][x] === num) return false;
            }
            
            // 检查列
            for (let x = 0; x < 9; x++) {
                if (grid[x][col] === num) return false;
            }
            
            // 检查3x3方格
            const startRow = Math.floor(row / 3) * 3;
            const startCol = Math.floor(col / 3) * 3;
            for (let i = 0; i < 3; i++) {
                for (let j = 0; j < 3; j++) {
                    if (grid[i + startRow][j + startCol] === num) return false;
                }
            }
            
            return true;
        }

        // 选择单元格
        function selectCell(cell) {
            if (cell.classList.contains('fixed')) {
                // 如果点击固定单元格，高亮相同数字
                highlightSameNumbers(cell.textContent);
                return;
            }
            
            // 移除其他单元格的选中状态
            const cells = document.getElementsByClassName('cell');
            Array.from(cells).forEach(c => c.classList.remove('selected'));
            
            // 添加选中状态
            cell.classList.add('selected');
            selectedCell = cell;

            // 如果点击空白格，清除所有高亮
            if (!cell.textContent) {
                clearSameNumberHighlight();
            }
        }

        // 打乱数组
        function shuffle(array) {
            for (let i = array.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [array[i], array[j]] = [array[j], array[i]];
            }
            return array;
        }

        // 启动计时器
        function startTimer() {
            if (timer) {
                clearInterval(timer);
            }
            timer = setInterval(() => {
                seconds++;
                const minutes = Math.floor(seconds / 60);
                const remainingSeconds = seconds % 60;
                document.querySelector('.timer').textContent = 
                    `时间: ${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
            }, 1000);
        }

        // 检查板子是否填满
        function isBoardFull() {
            for (let i = 0; i < 9; i++) {
                for (let j = 0; j < 9; j++) {
                    if (board[i][j] === 0) {
                        return false;
                    }
                }
            }
            return true;
        }

        // 检查解决方案是否正确
        function isSolutionCorrect() {
            for (let i = 0; i < 9; i++) {
                for (let j = 0; j < 9; j++) {
                    if (board[i][j] !== solution[i][j]) {
                        return false;
                    }
                }
            }
            return true;
        }
    </script>
</body>
</html>
      